<template>
  <!--更新需求弹框 -->
  <m-modal
    v-model="visible"
    :width="736"
    class="v-update-req"
    mask
    title="更新需求"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="_content g-pd-tb-25 g-pd-lr-25">
      <div class="com-panel">
        <div class="panel-title">已选择同步条目</div>
        <div class="panel-container">
          <a-table
            bordered
            :data-source="tableDataFiltered"
            :pagination="false"
            :scroll="{ y: 320 }"
            :height="320"
            size="small"
            class="update-req-table"
            rowKey="id"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onChange, onSelect:onSelect}"
          >
            <a-table-column key="reqId" title="ID" >
              <template slot-scope="row">
                {{ row.reqId }}
                <a-tooltip v-if="ignoreSyncReqIdMap[row.id]">
                 
                  <template slot="title">
                    已忽略
                  </template>
                  <img src="statics/icons/table/info-circle2.svg" class="tipImg">
                </a-tooltip>
          
              </template>
            </a-table-column>

            <a-table-column dataIndex='name' title="名称"/>
          
            <a-table-column dataIndex='changeName' title="变更字段"/>
         
            <a-table-column dataIndex='changeContent' title="变更内容"/>
            
          </a-table>
        </div>
      </div>
      <div class="hidden-ignore">
        <a-checkbox v-model="hiddenIgnore" >
          隐藏已忽略
        </a-checkbox>
      </div>
    </div>
    <div slot="footer">
      <a-button class="g-m-r-12" :disabled="btnDisabled" @click="ignore">忽略</a-button>
      <a-button  class="g-m-r-10" :disabled="btnDisabled" @click="cancelIgnore">取消忽略</a-button>
      <a-button type="primary" :disabled="btnDisabled" @click="handleOk">立即更新</a-button>
    </div>
  </m-modal>
</template>
<script>
import customModal from "../common/CustomModal";
import { Portal } from "src/components/common/Portal.vue";
import { API } from "@/constants/api";
import { treeForEach } from "@/util/common";
import { PropertyUtil } from "src/components/Attribute/comps/PropertyUtil";
import { graphHelper } from "src/api/GraphHelper";

const com = {
  name: "updateReqModal",
  components: {
    "m-modal": customModal
  },

  data() {
    return {
      visible: false,
      hiddenIgnore: true,
      tableData: [],
      selectedRows: [],
      selectedRowKeys: []
    };
  },
  computed: {
    ignoreSyncReqIdMap(){
      let obj = {};
      app.activeProject.config.ignoreSyncReqIds && app.activeProject.config.ignoreSyncReqIds.forEach((item) => {
        obj[item] = true;
      });
      return obj;
    },
    btnDisabled(){
      return this.selectedRows.length === 0;
    },
    tableDataFiltered(){
      if (this.hiddenIgnore){
        return this.tableData.filter(item => !this.ignoreSyncReqIdMap[item.id]);

      } else {
        return  this.tableData;
      }

    }
  },
  mounted() {
    this.visible = true;
    this.loadTreeData();
  },

  methods: {
    onChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    onSelect(record, selected, selectedRows)  {
      console.log('onSelect', record);
      this.selectedRows = selectedRows;
    },

    ignore() {
      const ignoreSyncReqIds = app.activeProject.config.ignoreSyncReqIds;

      this.selectedRows.forEach(item => {
        if (!(ignoreSyncReqIds && ignoreSyncReqIds.includes(item.id))){
          ignoreSyncReqIds.push(item.id);
        }
      });

    },
    cancelIgnore() {
      const ignoreSyncReqIds = app.activeProject.config.ignoreSyncReqIds;
      this.selectedRows.forEach(item => {
        ignoreSyncReqIds.remove(item.id);
        //// const index = ignoreSyncReqIds.findIndex((i) => i === item.id);
        //// if (index > -1) ignoreSyncReqIds.splice(index, 1);
      });
      
    },
    handleOk() {
      console.log("this.selectedRows", this.selectedRows);

      this.selectedRows.forEach(item => {

        const graphNode = graphHelper.getGraphNodeById(
          item.id,
          app.activeProjectId
        );
        item.changeAttr.forEach(it => {
          PropertyUtil.updateProperty(
            graphNode,
            it.propKey,
            it.newContent,
            false
          );

        });
      });
      if (this.selectedRows.length > 0){
        this.$bus.emit('project-modified');
      }
      this.visible = false;
      this.$emit("sure");
    },
    handleCancel() {
      this.visible = false;
      this.$emit("close");
    },

    async loadTreeData() {
      const reqMap = app.activeProject.config && app.activeProject.config.reqMap;
      console.log("reqMap---------", reqMap);

      const tableData = [];
      const remoteReqIds = Object.values(reqMap);

      const remoteReq = await this.getRemoteReq(remoteReqIds);
      console.log("remoteReq", remoteReq);
      
      Object.entries(reqMap).forEach(([modelId, remoteReqId]) => {
        const graphNode = graphHelper.getGraphNodeById(
          modelId,
          app.activeProjectId
        );
        //// 节点是否存在
        if (graphNode === undefined){
          delete reqMap[modelId];
        } else {
          const localReqName = PropertyUtil.getNodePropertyValue(
            graphNode,
            "Name"
          );
          const localReqText = PropertyUtil.getNodePropertyValue(
            graphNode,
            "Text"
          );
          const ReqId = PropertyUtil.getNodePropertyValue(
            graphNode,
            "ReqId"
          );
          //// debugger;
          if ( !remoteReq[remoteReqId] ) return;

          const remoteReqName = remoteReq[remoteReqId].name;
          const remoteReqText = remoteReq[remoteReqId].simpleText;
          if (localReqName === remoteReqName  && localReqText === remoteReqText){
            return;
          }
       
          const tableItem = {
            id: modelId,
            reqId: ReqId,
            name: localReqName,
            changeAttr: [],
            changeName: '',
            changeContent: ''
          };
          if (localReqName !== remoteReqName) {
            tableItem.changeAttr.push({ label: '名称', propKey: 'Name', oldContent: localReqName, newContent: remoteReqName,  });
          }
          if (localReqText !== remoteReqText) {
            tableItem.changeAttr.push({ label: 'Text', propKey: 'Text', oldContent: localReqText, newContent: remoteReqText, });
          }
          tableItem.changeName = tableItem.changeAttr.map(i => i.label).join('、'); 
          tableItem.changeContent = tableItem.changeAttr.map(i => i.newContent).join('、'); 
          tableData.push(tableItem);
        }
      });

      this.tableData = tableData;
      console.log(this.tableData);
    },
    getRemoteReq(reqIds) {
      return this.$post(API.REQUIRE_SERVICE_REQITEM_BATCH_DETAIL, {
        itemUuids: reqIds
      }).then(res => res.data);
      
    },
  }
};
export default com;
export const updateReqModal = new Portal(com, { single: true });
</script>
<style lang="scss" scoped>
.v-update-req {
	._content {
		padding: 25px;
		.com-panel {
			height: 406px;
			background: #ffffff;
			border-radius: 2px;
			border: 1px solid rgba(0, 0, 0, 0.15);
			.panel-title {
				width: 100%;
				height: 24px;
				padding-left: 10px;
				color: rgba(99, 78, 78, 0.85);
				line-height: 22px;
				background-color: #d4ebf8;
				border: 1px solid #b1cee2;
			}
			.panel-container {
				padding: 10px;
				overflow: auto;
        .tipImg{
          float: right;
          &:hover{
            cursor: pointer;
          }
          //// position: absolute;
          //// top: 0;
          //// left: 283px;
        }
			}
		}
		.hidden-ignore {
			text-align: right;
			margin-top: 10px;
		}
	}
}
</style>
